Imports System.IO
Imports System.Data
Imports System.Data.OleDb
Imports System.DirectoryServices

Partial Class wpAdminSearch
    Inherits System.Web.UI.Page

    Dim ad As New adsiClass
    Dim cr As New Crypto
    Dim result As SearchResult

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim conStr As String = ConfigurationManager.ConnectionStrings("ConStr").ToString
            Try
                ''''''''''''''''''''''''''''''''''''''''
                Dim qry2 As String
                qry2 = "select distinct city_name from city"
                Dim da2 As New OleDbDataAdapter
                da2 = New OleDbDataAdapter(qry2, conStr.ToString)
                Dim ds2 As New DataSet
                da2.Fill(ds2)
                Dim dt2 As New DataTable
                dt2 = ds2.Tables(0)
                Me.cboCity.DataSource = dt2
                Me.cboCity.DataTextField = "city_name"
                Me.cboCity.DataBind()

                ''''''''''''''''''''''''''''''''''''''''
                Dim qry3 As String
                qry3 = "select distinct state_name from state"
                Dim da3 As New OleDbDataAdapter
                da3 = New OleDbDataAdapter(qry3, conStr.ToString)
                Dim ds3 As New DataSet
                da3.Fill(ds3)
                Dim dt3 As New DataTable
                dt3 = ds3.Tables(0)
                Me.cboState.DataSource = dt3
                Me.cboState.DataTextField = "state_name"
                Me.cboState.DataBind()

                ''''''''''''''''''''''''''''''''''''''''
                Dim qry4 As String
                qry4 = "select distinct address_name from address"
                Dim da4 As New OleDbDataAdapter
                da4 = New OleDbDataAdapter(qry4, conStr.ToString)
                Dim ds4 As New DataSet
                da4.Fill(ds4)
                Dim dt4 As New DataTable
                dt4 = ds4.Tables(0)
                Me.cboAddress.DataSource = dt4
                Me.cboAddress.DataTextField = "address_name"
                Me.cboAddress.DataBind()

            Catch ex As Exception
                ad.SaveTextToFile(Now.ToLongDateString & " " & Now.ToLongTimeString & vbNewLine & ex.Message.ToString & vbNewLine & ex.ToString & vbNewLine & vbNewLine & ex.StackTrace.ToString & vbNewLine & vbNewLine & "DB Connectivity Error" & vbNewLine & "Connection String --> " & conStr.ToString)
                Session("msg") = "Error in connecting to database. Please contact your system administrator..."
                Response.Redirect("~/wpMessage.aspx")
            End Try
        End If

    End Sub

    Protected Sub Page_LoadComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadComplete
        Try
            Me.txtLoginName.Text = Session("loginName").ToString()
            search()
        Catch ex As NullReferenceException

        End Try
    End Sub

    Sub loadData()
        ad.userName = cr.Decrypt(Session("user").ToString(), "key1!")
        ad.userPassword = cr.Decrypt(Session("pas").ToString(), "key1!")
        Dim de As DirectoryEntry = ad.GetDirectoryEntry("LDAP://" & cr.Decrypt(Session("dc").ToString, "key1!"))
        Dim loginName As String
        Dim userVal As String = Me.txtLoginName.Text.ToString
        If userVal.Contains("\") Then
            Dim name As String = userVal
            Dim nameAr() As String = name.Split("\")
            loginName = nameAr(1)
        ElseIf userVal.Contains("@") Then
            Dim name As String = userVal
            Dim nameAr() As String = name.Split("@")
            loginName = nameAr(0)
        End If
        Dim dsh As New DirectorySearcher(de)
        dsh.SearchScope = SearchScope.Subtree
        dsh.Filter = "(&(objectClass=user) (sAMAccountName=" & loginName & "))"
        Try
            result = dsh.FindOne()
        Catch ex As Exception
            ad.SaveTextToFile(Now.ToLongDateString & " " & Now.ToLongTimeString & vbNewLine & ex.Message.ToString & vbNewLine & ex.ToString & vbNewLine & vbNewLine & ex.StackTrace.ToString & vbNewLine & vbNewLine & "Initial Connection String --> " & de.Path.ToString & vbNewLine & "User Name--> " & loginName & vbNewLine & "Filtered Connection String--> " & dsh.Filter.ToString & " ad user-" & ad.userName.ToString & " ad pass-" & ad.userPassword.ToString)
            Session("msg") = "Server was not accessible or wrong username/password was attempted..."
            Response.Redirect("~/wpMessage.aspx")
        End Try
        If Not result Is Nothing Then
            Dim fName, initials, lName, display, nick, address, city, state, zip, country, title, company, department, office, bPhone, fax, hPhone, mobile, pager, iPhone, assistant, notes, enabled As String
            Try
                fName = result.Properties("givenname").Item(0).ToString()
            Catch ex As ArgumentOutOfRangeException
                fName = ""
            End Try
            Try
                initials = result.Properties("initials").Item(0).ToString()
            Catch ex As ArgumentOutOfRangeException
                initials = ""
            End Try
            Try
                lName = result.Properties("sn").Item(0).ToString()
            Catch ex As ArgumentOutOfRangeException
                lName = ""
            End Try
            Try
                display = result.Properties("displayName").Item(0).ToString()
            Catch ex As ArgumentOutOfRangeException
                display = ""
            End Try
            Try
                nick = result.Properties("mailNickname").Item(0).ToString()
            Catch ex As ArgumentOutOfRangeException
                nick = ""
            End Try
            ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
            Try
                address = result.Properties("streetAddress").Item(0).ToString()
            Catch ex As ArgumentOutOfRangeException
                address = ""
            End Try
            Try
                city = result.Properties("l").Item(0).ToString()
            Catch ex As ArgumentOutOfRangeException
                city = ""
            End Try
            Try
                state = result.Properties("st").Item(0).ToString()
            Catch ex As ArgumentOutOfRangeException
                state = ""
            End Try
            Try
                zip = result.Properties("postalCode").Item(0).ToString()
            Catch ex As ArgumentOutOfRangeException
                zip = ""
            End Try
            Try
                country = result.Properties("co").Item(0).ToString()
            Catch ex As ArgumentOutOfRangeException
                country = ""
            End Try
            Try
                title = result.Properties("title").Item(0).ToString()
            Catch ex As ArgumentOutOfRangeException
                title = ""
            End Try
            Try
                company = result.Properties("company").Item(0).ToString()
            Catch ex As ArgumentOutOfRangeException
                company = ""
            End Try
            Try
                department = result.Properties("department").Item(0).ToString()
            Catch ex As ArgumentOutOfRangeException
                department = ""
            End Try
            Try
                office = result.Properties("physicalDeliveryOfficeName").Item(0).ToString()
            Catch ex As ArgumentOutOfRangeException
                office = ""
            End Try
            Try
                bPhone = result.Properties("telephoneNumber").Item(0).ToString()
            Catch ex As ArgumentOutOfRangeException
                bPhone = ""
            End Try
            Try
                fax = result.Properties("facsimileTelephoneNumber").Item(0).ToString()
            Catch ex As ArgumentOutOfRangeException
                fax = ""
            End Try
            Try
                hPhone = result.Properties("homePhone").Item(0).ToString()
            Catch ex As ArgumentOutOfRangeException
                hPhone = ""
            End Try
            Try
                mobile = result.Properties("mobile").Item(0).ToString()
            Catch ex As ArgumentOutOfRangeException
                mobile = ""
            End Try
            Try
                pager = result.Properties("pager").Item(0).ToString()
            Catch ex As ArgumentOutOfRangeException
                pager = ""
            End Try
            Try
                iPhone = result.Properties("ipPhone").Item(0).ToString()
            Catch ex As ArgumentOutOfRangeException
                iPhone = ""
            End Try
            Try
                assistant = result.Properties("msExchAssistantName").Item(0).ToString()
            Catch ex As ArgumentOutOfRangeException
                assistant = ""
            End Try
            Try
                notes = result.Properties("info").Item(0).ToString()
            Catch ex As ArgumentOutOfRangeException
                notes = ""
            End Try
            Try
                enabled = result.Properties("userAccountControl").Item(0).ToString()
            Catch ex As ArgumentOutOfRangeException
                enabled = ""
            End Try
            ''''''''''''''''''''''''''''''''
            Me.txtFName.Text = fName
            Me.txtInitials.Text = initials
            Me.txtLName.Text = lName
            Me.txtDisplay.Text = display
            Me.txtAlias.Text = nick
            ''''''''''''''''''''''''''''''''
            Try
                Me.cboAddress.Text = address
            Catch ex As Exception
                Me.cboAddress.Text = ""
            End Try
            Try
                Me.cboCity.Text = city
            Catch ex As Exception
                Me.cboCity.Text = ""
            End Try
            Try
                Me.cboState.Text = state
            Catch ex As Exception
                Me.cboState.Text = ""
            End Try

            Me.txtZip.Text = zip
            Me.txtCountry.Text = country
            Me.txtTitle.Text = title
            Me.txtCompany.Text = company
            Me.txtDepartment.Text = department
            Me.txtOffice.Text = office
            Me.txtBPhone.Text = bPhone
            Me.txtFax.Text = fax
            Me.txtHPhone.Text = hPhone
            Me.txtMobile.Text = mobile
            Me.txtPager.Text = pager
            Me.txtIPhone.Text = iPhone
            Me.txtAssistant.Text = assistant
            Me.txtNotes.Text = notes
            If enabled = "66048" Then  ''''Account is enabled
                Me.btnEnableDisableUser.Text = "Disable User"
            ElseIf enabled = "66050" Then  '''''Account is disabled
                Me.btnEnableDisableUser.Text = "Enable User"
            Else
                Me.btnEnableDisableUser.Enabled = False
            End If
            If Me.txtAlias.Text <> "" Then
                Me.btnUpdate.Enabled = True
                Me.btnEnableDisableUser.Enabled = True
                Me.btnGroups.Enabled = True
                Me.btnResetPassword.Enabled = True
            Else
                Me.btnUpdate.Enabled = False
                Me.btnEnableDisableUser.Enabled = False
                Me.btnGroups.Enabled = False
                Me.btnResetPassword.Enabled = False
            End If
        End If
    End Sub

    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        search()
    End Sub

    Sub search()
        If Me.txtLoginName.Text <> "" Then
            Session("loginName") = Me.txtLoginName.Text
        End If
        Me.loadData()
    End Sub

    Protected Sub btnUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
        ad.userName = cr.Decrypt(Session("user").ToString(), "key1!")
        ad.userPassword = cr.Decrypt(Session("pas").ToString(), "key1!")
        '''''''''''''''''''''''''''''
        Dim fieldNames() As String = {"givenname", "initials", "sn", "displayName", "mailNickname", "streetAddress", "l", "st", "postalCode", "title", "company", "department", "physicalDeliveryOfficeName", "telephoneNumber", "facsimileTelephoneNumber", "homePhone", "mobile", "pager", "ipPhone", "info", "co", "", "", "", ""}
        Dim fieldValues(20) As String
        Dim eList() As String = {"streetAddress", "physicalDeliveryOfficeName", "l", "st", "telephoneNumber", "facsimileTelephoneNumber", "homePhone", "mobile", "pager", "ipPhone", "info"}
        '''''''''''''''''''''''''''''''''
        fieldValues(0) = Me.txtFName.Text
        fieldValues(1) = Me.txtInitials.Text
        fieldValues(2) = Me.txtLName.Text
        fieldValues(3) = Me.txtDisplay.Text
        fieldValues(4) = Me.txtAlias.Text
        '''''''''''''''''''''''''''''''''
        fieldValues(5) = Me.cboAddress.Text
        fieldValues(6) = Me.cboCity.Text
        fieldValues(7) = Me.cboState.Text
        fieldValues(8) = Me.txtZip.Text
        fieldValues(9) = Me.txtTitle.Text
        fieldValues(10) = Me.txtCompany.Text
        fieldValues(11) = Me.txtDepartment.Text
        fieldValues(12) = Me.txtOffice.Text
        fieldValues(13) = Me.txtBPhone.Text
        fieldValues(14) = Me.txtFax.Text
        fieldValues(15) = Me.txtHPhone.Text
        fieldValues(16) = Me.txtMobile.Text
        fieldValues(17) = Me.txtPager.Text
        fieldValues(18) = Me.txtIPhone.Text
        fieldValues(19) = Me.txtNotes.Text
        fieldValues(20) = Me.txtCountry.Text
        '''''''''''''''''''''''''''''''''''''''
        Dim i, j As Integer
        For i = 5 To 20
            If fieldValues(i) = "" Then
                fieldValues(i) = " "
            End If
        Next
        ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        Me.loadData()
        ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        Dim dey As DirectoryEntry = ad.GetDirectoryEntry(result.Path)

        For j = 5 To 20
            Dim val As String
            If fieldValues(j) <> " " Then
                val = fieldValues(j).Trim()
            Else
                val = fieldValues(j)
            End If
            If Array.IndexOf(eList, fieldNames(j)) >= 0 Then
                ad.SetProperty(dey, fieldNames(j), val)
            End If

        Next
        Try
            dey.CommitChanges()
        Catch ex As Exception
            ad.SaveTextToFile(Now.ToLongDateString & " " & Now.ToLongTimeString & vbNewLine & ex.Message.ToString & vbNewLine & "Connection String --> " & dey.Path.ToString)
            Session("msg") = "Access denied. You are not authorized to change some data. Please contact system administrator..."
            Response.Redirect("~/wpMessage.aspx")
        End Try

        dey.Close()
        Me.loadData()
    End Sub

    Protected Sub btnResetPassword_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnResetPassword.Click
        Session("loginName") = Me.txtLoginName.Text
        Response.Redirect("~/wpAdminResetPassword.aspx")
    End Sub

    Protected Sub btnEnableDisableUser_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnEnableDisableUser.Click
        ad.userName = cr.Decrypt(Session("user").ToString, "key1!")
        ad.userPassword = cr.Decrypt(Session("pas").ToString, "key1!")
        Dim loginName As String = Me.txtAlias.Text
        Dim result As SearchResult
        '''''''Declare Username and Password before you make this object...
        Dim de As DirectoryEntry = ad.GetDirectoryEntry("LDAP://" & cr.Decrypt(Session("dc").ToString, "key1!") & "")
        Dim dsh As New DirectorySearcher(de)
        dsh.SearchScope = SearchScope.Subtree
        dsh.Filter = "(&(objectClass=user) (sAMAccountName=" & loginName & "))"
        Try
            result = dsh.FindOne()
            If Me.btnEnableDisableUser.Text = "Enable User" Then
                ad.EnableAccount(result.Path)
            ElseIf Me.btnEnableDisableUser.Text = "Disable User" Then
                ad.disableUser(result.Path)
            End If
        Catch ex As Exception
            ad.SaveTextToFile(Now.ToLongDateString & " " & Now.ToLongTimeString & vbNewLine & ex.Message.ToString & vbNewLine & ex.ToString & vbNewLine & vbNewLine & ex.StackTrace.ToString & vbNewLine & vbNewLine & "DB Connectivity Error" & vbNewLine)
            Session("msg") = "Access denied. You are not authorized to change some data. Please contact system administrator..."
            Response.Redirect("~/wpMessage.aspx")
        End Try
        Me.loadData()

    End Sub

    Protected Sub btnGroups_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGroups.Click
        Session("loginName") = Me.txtLoginName.Text.ToString
        Response.Redirect("~/wpAdminManageGroups.aspx")
    End Sub


End Class
